package edge.display.backend.MsgDistributer.Redis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import edge.display.backend.KEY_STORE;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;

@Component
public class AsyncRedisSave {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Async
    public void forEntity(Object object, String prefix) {
        if (Objects.nonNull(object)) {
            forJSON(JSON.toJSONString(object), prefix);
        }
    }

    @Async
    public void forJSON(String jsonString, String prefix) {
        if (JSON.isValid(jsonString)) {
            forMap(JSONObject.parseObject(jsonString), prefix);
        }
    }

    @Async
    public void forMap(Map<String, ?> map, String identifier, String prefix) {
        String orgId = map.getOrDefault(identifier, null).toString();
        String id = prefix.concat(orgId);
        stringRedisTemplate.opsForHash().putAll(id, map);
    }

    @Async
    public void forMap(Map<String, ?> map, String prefix) {
        forMap(map, KEY_STORE.DEFAULT_IDENTIFIER, prefix);
    }

    @Async
    public void forMap(Map<String, ?> map) {
        forMap(map, KEY_STORE.DEFAULT_IDENTIFIER, "");
    }
}
